<?php

/* 会员控制器 */

class UserApp extends BackendApp
{
    var $_user_mod;

    function __construct()
    {
        $this->UserApp();
    }

    function UserApp()
    {
        parent::__construct();
        $this->_user_mod =& m('member');
    }

    function index()
    {
        //当前用户类型
        $type = $this->visitor->get('type');
        $this->assign('type', $type);
        if (!empty($type)) {
            echo "您无权操作";
            exit;
        }
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => $_GET['field_name'],
                'name' => 'field_value',
                'equal' => 'like',
            ),
            array(
                'field' => 'grade',
                'name' => 'grade',
                'equal' => '=',
            ),

        ));
        $where = ' and prevuid=0 and member.type<>10 ';
        //更新排序
        if (isset($_GET['sort']) && !empty($_GET['order'])) {
            $sort = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order, array('asc', 'desc'))) {
                $sort = 'reg_time';
                $order = 'desc';
            }
        } else {
            if (isset($_GET['sort']) && empty($_GET['order'])) {
                $sort = strtolower(trim($_GET['sort']));
                $order = "";
            } else {
                $sort = 'reg_time';
                $order = 'desc';
            }
        }
        $page = $this->_get_page();

        $db =& db();
        $sql = "SELECT member.*,d1.d_value,p1.o_name, s.store_id,user_priv.store_id as
priv_store_id,user_priv.privs, member.user_id FROM zys_member member 
LEFT JOIN zys_store s ON member.user_id=s.store_id LEFT JOIN zys_user_priv user_priv 
ON member.user_id=user_priv.user_id AND user_priv.store_id = '0'
LEFT JOIN zys_dictionary d1 ON member.type=d1.d_key AND d1.d_code='member_type'
LEFT JOIN zys_operator p1 ON member.unit=p1.o_tid 
WHERE 1=1 " . $conditions . $where . " ORDER BY $sort $order LIMIT " . $page['limit'];

        $users = $db->getAll($sql);

        $sql2 = "select count(*)  FROM zys_member member
LEFT JOIN zys_store s ON member.user_id=s.store_id LEFT JOIN zys_user_priv user_priv 
ON member.user_id=user_priv.user_id AND user_priv.store_id = '0'
LEFT JOIN zys_dictionary d1 ON member.type=d1.d_key AND d1.d_code='member_type'
LEFT JOIN zys_operator p1 ON member.unit=p1.o_tid 
WHERE 1=1 " . $conditions . $where;
        $users_count = $db->getone($sql2);

        foreach ($users as $key => $val) {
            if ($val['priv_store_id'] == 0 && $val['privs'] != '') {
                $users[$key]['if_admin'] = true;
            }
        }
        $this->assign('users', $users);
        $page['item_count'] = $users_count;
        $this->_format_page($page);
        $this->assign('filtered', $conditions ? 1 : 0); //是否有查询条件
        $this->assign('page_info', $page);

        $sql = "select d.d_key,d.d_value from zys_dictionary as d WHERE d.d_code='m_grade'";
        $grade = $db->getAll($sql);
        $grades = array();
        foreach ($grade as $key => $val) {
            $grades[$val['d_key']] = $val['d_value'];
        }
        $this->assign('grades', $grades);
        /* 导入jQuery的表单验证插件 */
        $this->import_resource(array(
            'script' => 'jqtreetable.js,inline_edit.js',
            'style' => 'res:style/jqtreetable.css'
        ));
        $this->assign('query_fields', array(
            'user_name' => LANG::get('user_name'),
            'email' => LANG::get('email'),
            'real_name' => LANG::get('real_name'),
            //            'phone_tel' => LANG::get('phone_tel'),
            //            'phone_mob' => LANG::get('phone_mob'),
        ));
        $this->assign('sort_options', array(
            'reg_time DESC' => LANG::get('reg_time'),
            'last_login DESC' => LANG::get('last_login'),
            'logins DESC' => LANG::get('logins'),
        ));
        $this->display('user.index.html');
    }

    function add()
    {
        $db =& db();
        $user_type = $utype = isset($_GET['utype']) ? intval($_GET['utype']) : -1;
        //当前用户类型
        $type = $this->visitor->get('type');
        $this->assign('type', $type);
        $this->assign('utype', $utype);
        if (!IS_POST) {
            /* 导入jQuery的表单验证插件 */
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js'));
            //是否设置头像
            //$ms =& ms();
            //$this->assign('set_avatar', $ms->user->set_avatar());
            $sql = "select d.d_key,d.d_value from zys_dictionary as d WHERE d.d_code='m_grade'";
            $grade = $db->getAll($sql);
            $grades = array();
            foreach ($grade as $key => $val) {
                $grades[$val['d_key']] = $val['d_value'];
            }
            $this->assign('grades', $grades);
            $this->display('user.form.html');
        } else {
            $user_name = trim($_POST['user_name']);
            $password = trim($_POST['password']);
            $email = trim($_POST['email']);
            $phone_tel = trim($_POST['phone_tel']);
            $grade = trim($_POST['grade']);

            if (strlen($user_name) < 3 || strlen($user_name) > 25) {
                $this->show_warning('user_name_length_error');

                return;
            }

            if (strlen($password) < 6 || strlen($password) > 20) {
                $this->show_warning('password_length_error');

                return;
            }

            if (!empty($email)) {
                if (!is_email($email)) {
                    $this->show_warning('email_error');

                    return;
                }
            }

            if (!preg_match("/^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/", $phone_tel)) {

                $this->show_warning('手机错误');
                return;
            }
            /* 连接用户系统 */
            $ms =& ms();

            /* 检查名称是否已存在 */
            if (!$ms->user->check_username($user_name)) {
                $this->show_warning($ms->user->get_error());
                return;
            }
            if ($utype == -1) $user_type = $type;
            $prevuid = $type == 0 ? 0 : $this->visitor->get('user_id');
            /* 保存本地资料 */
            $data = array(
                'real_name' => trim($_POST['real_name']),
                'gender' => intval($_POST['gender']),
                'phone_tel' => $_POST['phone_tel'],
                'unit' => intval($_POST['unit']),
                'type' => intval($user_type),
                'prevuid' => $prevuid,
                'grade' => $grade,
                'giveauth' => isset($_POST['giveauth']) ? intval($_POST['giveauth']) : 0
                //                'phone_mob' => $_POST['phone_mob'],
                //				  'im_qq'     => $_POST['im_qq'],
                // 				  'im_msn'    => $_POST['im_msn'],
                //                'im_skype'  => $_POST['im_skype'],
                //                'im_yahoo'  => $_POST['im_yahoo'],
                //                'im_aliww'  => $_POST['im_aliww'],
                // 				  'reg_time'  => gmtime(),
            );
            if (in_array($utype, array(2, 3, 4))) {
                $data['subtype'] = 1;
            }
            /* 到用户系统中注册 */
            $user_id = $ms->user->register($user_name, $password, $email, $data);
            if (!$user_id) {
                $this->show_warning($ms->user->get_error());

                return;
            }

            /*if (!empty($_FILES['portrait']))
             {
                $portrait = $this->_upload_portrait($user_id);
                if ($portrait === false)
                {
                return;
                }

                $portrait && $this->_user_mod->edit($user_id, array('portrait' => $portrait));
                $portrait && $this->_user_mod->edit($user_id, array('headimgurl' => $portrait));
                }*/


            $this->show_message('add_ok', '返回会员', 'index.php?app=user&act=edit&id=' . $user_id);
        }
    }

    /*检查会员名称的唯一性*/
    function check_user()
    {
        $user_name = empty($_GET['user_name']) ? null : trim($_GET['user_name']);
        if (!$user_name) {
            echo ecm_json_encode(false);
            return;
        }

        /* 连接到用户系统 */
        $ms =& ms();
        echo ecm_json_encode($ms->user->check_username($user_name));
    }

    function edit()
    {
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        if (!IS_POST) {
            /* 是否存在 */
            $sql = "select m.*,op.o_name from zys_member as m left join zys_operator as op on m.unit =op.o_tid where m.user_id=" . $id;
            $db = &db();
            $user = $db->getRow($sql);
            if (!$user) {
                $this->show_warning('user_empty');
                return;
            }
            $type = $this->visitor->get('type');
            if ($type != 0) {
                if ($type != $user['type']) {
                    $this->show_warning('您无权操作');
                }
            }
            $this->assign('utype', $user['type']);
            $sql = "select d.d_key,d.d_value from zys_dictionary as d WHERE d.d_code='m_grade'";
            $grade = $db->getAll($sql);
            $grades = array();
            foreach ($grade as $key => $val) {
                $grades[$val['d_key']] = $val['d_value'];
            }
            $this->assign('grades', $grades);

            /*
             $ms =& ms();
             $this->assign('set_avatar', $ms->user->set_avatar($id));*/
            $this->assign('user', $user);
            $this->assign('phone_tel', explode('-', $user['phone_tel']));
            /* 导入jQuery的表单验证插件 */
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js'));
            $this->display('user.form.html');
        } else {
            $prevuid = $this->visitor->get('type') == 0 ? 0 : $this->visitor->get('user_id');
            $data = array(
                'real_name' => trim($_POST['real_name']),
                'gender' => intval($_POST['gender']),
                'phone_tel' => $_POST['phone_tel'],
                'unit' => intval($_POST['unit']),
                'type' => intval($_POST['type']),
                'prevuid' => $prevuid,
                'grade' =>trim($_POST['grade']),
                'giveauth' => isset($_POST['giveauth']) ? intval($_POST['giveauth']) : 0
                //                'phone_mob' => $_POST['phone_mob']
                //   			  'im_qq'     => $_POST['im_qq'],
                //                'im_msn'    => $_POST['im_msn'],
                //                'im_skype'  => $_POST['im_skype'],
                //                'im_yahoo'  => $_POST['im_yahoo'],
                //                'im_aliww'  => $_POST['im_aliww'],
            );
            if (!empty($_POST['password'])) {
                $password = trim($_POST['password']);
                if (strlen($password) < 6 || strlen($password) > 20) {
                    $this->show_warning('password_length_error');

                    return;
                }
            }

            if (!empty($email)) {
                if (!is_email($email)) {
                    $this->show_warning('email_error');

                    return;
                }
            }

            if (!preg_match("/^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/", trim($_POST['phone_tel']))) {

                $this->show_warning('手机错误');
                return;
            }

            /*if (!empty($_FILES['portrait']))
             {
                $portrait = $this->_upload_portrait($id);
                if ($portrait === false)
                {
                return;
                }
                $data['portrait'] = $portrait;
                $data['headimgurl'] = $portrait;

                }*/

            /* 修改本地数据 */
            $this->_user_mod->edit($id, $data);

            /* 修改用户系统数据 */
            $user_data = array();
            !empty($_POST['password']) && $user_data['password'] = trim($_POST['password']);
            !empty($_POST['email']) && $user_data['email'] = trim($_POST['email']);
            if (!empty($user_data)) {
                $ms =& ms();
                $ms->user->edit($id, '', $user_data, true);
            }

            $this->show_message('edit_ok', 'edit_again', 'index.php?app=user&act=edit&id=' . $id
            );
        }
    }

    //货主列表
    function choosehz()
    {
        $db =& db();
        $page = $this->_get_page();
        $o_name = empty($_GET['o_name']) ? '' : $_GET['o_name'];
        $sqlw = " o_consignor=1 ";
        if ($o_name) {
            $sqlw .= " and o_name like '%" . $o_name . "%'";
        }
        $sql = "select * from zys_operator WHERE $sqlw";
        $page['item_count'] = $db->getOne($sql);

        $this->_format_page($page);
        $this->assign('page_info', $page);

        $sql = "SELECT * FROM zys_operator WHERE $sqlw limit $page[limit]";
        $hz = $db->getAll($sql);
        $this->assign('hz', $hz);
        $this->display('user.choosehz.html');
    }

    //选择承运商
    function chooseop()
    {
        $db =& db();
        $page = $this->_get_page();

        $o_name = empty($_GET['o_name']) ? '' : $_GET['o_name'];

        $sqlw = " o_carrier=1 ";
        if ($o_name) {
            $sqlw .= " and o_name like '%" . $o_name . "%'";
        }
        $sql = "select * from zys_operator WHERE $sqlw";
        $page['item_count'] = $db->getOne($sql);

        $this->_format_page($page);
        $this->assign('page_info', $page);

        $sql = "SELECT * FROM zys_operator WHERE $sqlw limit $page[limit]";
        $carrier = $db->getAll($sql);

        $this->assign('carrier', $carrier);

        $this->display('user.chooseop.html');
    }


    function ajax_col()
    {
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        $column = empty($_GET['column']) ? '' : trim($_GET['column']);
        $value = isset($_GET['value']) ? trim($_GET['value']) : '';
        $data = array();

        if (in_array($column, array('del'))) {
            $data[$column] = $value;
            $this->_user_mod->edit($id, $data);
            if (!$this->_user_mod->has_error()) {
                echo ecm_json_encode(true);
            }
        } else {
            return;
        }
        return;
    }

    function drop()
    {
        $db =& db();
        $id = isset($_GET['id']) ? trim($_GET['id']) : '';
        if (!$id) {
            $this->show_warning('no_user_to_drop');
            return;
        }
        $admin_mod =& m('userpriv');
        if (!$admin_mod->check_admin($id)) {
            $this->show_message('cannot_drop_admin',
                'drop_admin', 'index.php?app=admin');
            return;
        }

        $ids = explode(',', $id);

        /* 连接用户系统，从用户系统中删除会员 */
        $ms =& ms();
        if (!$ms->user->drop($ids)) {
            foreach ($ids as $k => $v) {
                $sql = "select username from cw_member where user_id=" . $v;
                $username = $db->getOne();

                if ($username) {
                    $url = "http://192.168.0.189:9090/plugins/userService/userservice?type=delete&secret=0wBfHo6f&username=" . $username;
                    $f = fopen($url, 'r');
                    $response = fread($f, 1024);
                    fclose($f);
                }
            }
            $this->show_warning($ms->user->get_error());

            return;
        }

        $this->show_message('drop_ok', '返回列表', 'index.php?app=user');
    }

    /**
     * 上传头像
     *
     * @param int $user_id
     * @return mix false表示上传失败,空串表示没有上传,string表示上传文件地址
     */
    function _upload_portrait($user_id)
    {
        $file = $_FILES['portrait'];
        if ($file['error'] != UPLOAD_ERR_OK) {
            return '';
        }

        import('uploader.lib');
        $uploader = new Uploader();
        $uploader->allowed_type(IMAGE_FILE_TYPE);
        $uploader->addFile($file);
        if ($uploader->file_info() === false) {
            $this->show_warning($uploader->get_error(), 'go_back', 'index.php?app=user&amp;act=edit&amp;id=' . $user_id);
            return false;
        }
        $imgname = gmtime();
        $uploader->root_dir(ROOT_PATH);
        return $uploader->save('data/files/mall/portrait/' . ceil($user_id / 500), $imgname);
    }
}

?>
